import { defineStore } from 'pinia';
import { TAGS_VIEW } from '@/constant';
import { getItem, setItem } from '@/utils/storage';
import variables from '@/styles/js.module.scss';
export const useAppStore = defineStore('tag', {
  state: () => {
    return {
      sidebarOpened: true,
      variables: variables,
      tagsViewList: getItem(TAGS_VIEW) || []
    };
  },
  actions: {
    triggerSidebarOpened() {
      this.sidebarOpened = !this.sidebarOpened;
    },
    /**
     * 初始化 tagsList
     */
    initTagsViewList() {
      this.tagsViewList = [];
    },
    /**
     * 添加 tags
     */
    addTagsViewList(tag) {
      const isFind = this.tagsViewList.find((item) => {
        return item.path === tag.path;
      });
      // 处理重复
      if (!isFind && tag.meta && tag.meta.title) {
        this.tagsViewList.push(tag);
        setItem(TAGS_VIEW, this.tagsViewList);
      }
    },
    /**
     * 为指定的 tag 修改 title
     */
    changeTagsView({ index, tag }) {
      this.tagsViewList[index] = tag;
      setItem(TAGS_VIEW, this.tagsViewList);
    },
    /**
     * 删除 tag
     * @param {type: 'other'||'right'||'index', index: index} payload
     */
    removeTagsView(payload) {
      if (payload.type === 'index') {
        this.tagsViewList.splice(payload.index, 1);
        return;
      } else if (payload.type === 'other') {
        this.tagsViewList.splice(
          payload.index + 1,
          this.tagsViewList.length - payload.index + 1
        );
        this.tagsViewList.splice(0, payload.index);
      } else if (payload.type === 'right') {
        this.tagsViewList.splice(
          payload.index + 1,
          this.tagsViewList.length - payload.index + 1
        );
      }
      setItem(TAGS_VIEW, this.tagsViewList);
    }
  }
});
